<template>
  <div class="defect-chart-container">
    <div class="chart-header">
      <h3>缺陷类型分布</h3>
      <el-button type="primary" size="small" @click="refreshChart">刷新数据</el-button>
    </div>
    <div ref="chartRef" class="chart" style="width: 100%; height: 400px;"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import * as echarts from 'echarts'
import { listReports } from "@/api/quality-service/reports"

const chartRef = ref(null)
let chartInstance = null

// 模拟数据 - 实际应从API获取
const defectTypes = ref([
  { name: '外观缺陷', value: 0 },
  { name: '尺寸偏差', value: 0 },
  { name: '功能故障', value: 0 },
  { name: '材料问题', value: 0 },
  { name: '装配问题', value: 0 },
  { name: '其他缺陷', value: 0 }
])

// 初始化图表
const initChart = () => {
  if (!chartRef.value) return

  chartInstance = echarts.init(chartRef.value)

  const option = {
    title: {
      text: '缺陷类型分布',
      subtext: '基于不合格品报告数据',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: defectTypes.value.map(item => item.name)
    },
    series: [
      {
        name: '缺陷类型',
        type: 'pie',
        radius: ['50%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: defectTypes.value
      }
    ]
  }

  chartInstance.setOption(option)
}

// 从API获取数据并更新图表
const fetchDataAndUpdateChart = async () => {
  try {
    const response = await listReports({
      pageNum: 1,
      pageSize: 1000 // 获取足够多的数据
    })

    // 统计缺陷类型
    const defectCounts = {}
    response.rows.forEach(report => {
      const typeId = report.defectTypeId
      defectCounts[typeId] = (defectCounts[typeId] || 0) + 1
    })

    // 更新缺陷类型数据
    // 注意：这里假设defectTypeId对应我们预设的缺陷类型
    // 实际应用中，您可能需要从API获取缺陷类型名称
    defectTypes.value = [
      { name: '表面划痕', value: defectCounts['1'] || 0 },
      { name: '尺寸超差', value: defectCounts['2'] || 0 },
      { name: '漏焊/虚焊', value: defectCounts['3'] || 0 },
      { name: '漆面不均', value: defectCounts['4'] || 0 },
      { name: '物料缺失', value: defectCounts['5'] || 0 },
      { name: '其他缺陷', value: defectCounts['6'] || 0 }
    ]

    // 过滤掉值为0的项
    const filteredData = defectTypes.value.filter(item => item.value > 0)

    // 更新图表
    if (chartInstance) {
      chartInstance.setOption({
        legend: {
          data: filteredData.map(item => item.name)
        },
        series: [{
          data: filteredData
        }]
      })
    }
  } catch (error) {
    console.error('获取缺陷类型数据失败:', error)
  }
}

// 刷新图表数据
const refreshChart = () => {
  fetchDataAndUpdateChart()
}

// 响应式调整图表大小
const resizeChart = () => {
  if (chartInstance) {
    chartInstance.resize()
  }
}

onMounted(() => {
  initChart()
  fetchDataAndUpdateChart()
  window.addEventListener('resize', resizeChart)
})

onBeforeUnmount(() => {
  if (chartInstance) {
    chartInstance.dispose()
  }
  window.removeEventListener('resize', resizeChart)
})
</script>

<style scoped>
.defect-chart-container {
  background-color: #fff;
  border-radius: 4px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.chart-header h3 {
  margin: 0;
  font-size: 16px;
  color: #333;
}
</style>